package cli.view;

import java.io.PrintWriter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ProgressBar {
    private int filesNum;
    private long totalSize;
    public volatile int copiedNum = 0;
    public volatile long copiedSize = 0;
    private long begin = System.currentTimeMillis();

    public ProgressBar(int filesNum, long totalSize) {
        this.filesNum = filesNum;
        this.totalSize = totalSize;
    }

    public void update(int copiedNum, long copiedSize) {
        this.copiedNum = copiedNum;
        this.copiedSize = copiedSize;
    }

    public void wait(PrintWriter out, Runnable runnable) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<?> future = executor.submit(runnable);
        for (int i = 0; ; i++) {
            double percent = copiedSize /(double) totalSize;
            long now = System.currentTimeMillis();
            long secondsNum = (now - begin) / 1000;
            long speed = secondsNum == 0 ? 0 : copiedSize / secondsNum;
            long eta = speed == 0 ? 0 : (totalSize - copiedSize) / speed;
            out.printf("\r%s %s %s/%s %s/s eta%s   ", Formats.percent(percent), Formats.progressBar(30, percent), Formats.memorySize(copiedSize), Formats.memorySize(totalSize), Formats.memorySize(speed), Formats.elapsedTime(eta));
            try {
                Thread.sleep(200);
            } catch (InterruptedException ignored) {

            }
            if (future.isDone()) {
                out.printf("\r%s %s %s/%s %s/s eta%s   ", Formats.percent(1.0), Formats.progressBar(30, 1.0), Formats.memorySize(copiedSize), Formats.memorySize(totalSize), Formats.memorySize(speed), Formats.elapsedTime(eta));
                break;
            }
        }
        out.println();
    }
}
